<?php

use Biz\model\Album\AlbumListModel;
use Biz\service\Album\AlbumListService;
use Doraemon\model\ForbiddenWord\ForbiddenSceneWord as ForbiddenSceneWordModel;
use Doraemon\service\ForbiddenWord\ForbiddenSceneWord;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;

class SaveAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;
    const PUBLIC_YES = 0;
    const PUBLIC_NO = 7;

    /**
     * @throws \Exception
     */
    public function main()
    {
        $currUid = $this->uid;
        if (!$currUid) {
            throw new \Exception("请登录重试！");
        }
        $albumId = $this->getRequest()->getPost('album_id', '');
        $title = $this->getRequest()->getPost('title', '');
        $isOpen = $this->getRequest()->getPost('is_public', 0); //是否公开  0公开，7不公开
        $wikiList = $this->getRequest()->getPost('wiki_list', '');

        $isCanBuiltAlbum = AlbumListService::checkIsCanBuiltAlbum($currUid);
        if(!$isCanBuiltAlbum){
            throw new Exception("保存失败，你还没有创建权限哦~");
        }

        $wikiList = json_decode($wikiList, true);
        $countWiki = count($wikiList);

        Log::info('好物清单添加/编辑-Album/Save', ['$albumId' => $albumId, '$title' => $title, '$isOpen' => $isOpen, '$wikiList' => $wikiList, '$countWiki' => $countWiki]);

        if (empty($title) || $countWiki < 1) {
            throw new Exception('必须输入清单标题,并添加一件商品');
        }

        if ($countWiki > AlbumListModel::ALBUM_WIKI_LIMIT) {
            throw new Exception('商品数量超过限制');
        }

        //敏感词过滤
        $text = $title . ',' . implode(',', array_filter(array_column($wikiList, 'content')));

        $remarkForbidden = new ForbiddenSceneWord(ForbiddenSceneWordModel::CONTENT, $text);
        if ($remarkForbidden->getHit()) {
            if($remarkForbidden->getPublish()){ //0不允许发布 1允许发布
                //敏感词场景处理方式 可以发布 这里不做任何处理
            }else{
                throw new Exception('嘻嘻，别闹啦~删掉敏感信息再发布吧');
            }
        }

        if (self::PUBLIC_YES == $isOpen) { //表示公开
            $status = AlbumListModel::STATUS_UNTREATED;
        } elseif (self::PUBLIC_NO == $isOpen) {//表示用户不公开 ，设置为私密
            $status = AlbumListModel::STATUS_USER_PRIVATE;
        } else {
            $status = 0; //兜底
        }
        $albumData = [
            'uid' => $currUid,
            'title' => $title,
            'status' => $status,
            'wiki_list' => $wikiList,
        ];
        $albumId = AlbumListService::addOrUpdateAlbum($albumData, $albumId);
        $data['album_link'] = Hhzurl::getAlbumDetailNiceLivingLink($albumId);
        $data['album_id'] = $albumId;
        $this->setSuccess($data, self::API_CODE_SUCCES);


    }
}